﻿using System;
using System.Collections.Generic;
using System.Windows.Media;
using EzDesk.Clients.Utility;
using EzDesk.DevHelper.DbMgr.Views;
using EzDesk.Utility.Log;

namespace EzDesk.DevHelper.DbMgr.Presenters
{

    public class XamlStringToFrameworkElement : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return null;

            if (value.GetType() != typeof(string))
                throw new Exception("Input object should be a string!");

            try
            {
                LogEx.TRACE("ConvertXamlToUIElement", string.Format("XAML Source: {0}", value));
                return System.Windows.Markup.XamlReader.Parse(value.ToString());
            }
            catch (Exception exp)
            {
                LogEx.EXCEPT("ConvertXamlToUIElement", "XAML Parse 错误", exp);
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class WpfPreviewPresenter
    {
        private WpfPreview _view;

        public WpfPreview View
        {
            get { return _view; }
            set { _view = value; }
        }

        public WpfPreviewPresenter(WpfPreview view)
        {
            this._view = view;
        }

        public void Preview(string EZMLStr, string appPortalUrl = "http://www.google.com")
        {
            var parameters = new List<KeyValuePair<string, string>>
                             {
                                 new KeyValuePair<string, string>(
                                     "appportalurl", appPortalUrl)
                             };
            var feedTransform = new XamlFeedTransform();
            string xamlString;
            try
            {
                xamlString = feedTransform.Transform(EZMLStr, parameters.ToArray());
                this._view.EZMLTxt.Text = xamlString;

                var element = System.Windows.Markup.XamlReader.Parse(xamlString);
                this._view.PreviewCtt.Content = element;
                
                this._view.ErrorTxt.Text = "Good!:)";
                this._view.ErrorLit.Fill = new SolidColorBrush(Colors.Green);
            }
            catch (Exception exp)
            {
                this._view.ErrorTxt.Text ="Error!:\n\t"+ exp.Message;
                this._view.ErrorLit.Fill = new SolidColorBrush(Colors.Red);
            }

        }
    }
}
